﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using JobDescOnline.Presentation.Models;
using eq.CoreBase.View;
using eq.CoreBase.Control;

namespace JobDescOnline.Presentation.Controllers
{
    public class DepartmentController : Controller
    {
        //
        // GET: /Department/

        public JobDescDBEntities1 db = new JobDescDBEntities1();

        public ActionResult Index()
        {
            int pagesize = 10;
            int page = Request.QueryString["page"] != null ? Convert.ToInt16(Request.QueryString["page"]) : 1;
            string sort = Request.QueryString["sort"] != null ? Request.QueryString["sort"] : "ID";
            string direction = Request.QueryString["direction"] != null ? Request.QueryString["direction"] : "ASC";
            int total = 0;

            var model = Departments.RetrieveByFilterAndPage(page, pagesize, sort, direction);
            total = Departments.RetrieveByFilter();

            ViewData["Dir"] = direction.ToLower() == "asc" ? "desc" : "asc";

            PagingGenerated pager = new PagingGenerated(page, pagesize, total, "/Department/AjaxTable", true, ">> next", true, "<< previous");
            ViewData["Pagination"] = pager.PaginationLink();
            return View(model);
        }

        public ActionResult AjaxTable()
        {
            int pagesize = 10;
            int page = Request.QueryString["page"] != null ? Convert.ToInt16(Request.QueryString["page"]) : 1;
            List<FilterData> filters = Request.Form["filter"] != null ? new JavaScriptSerializer().Deserialize<List<FilterData>>(Request.Form["filter"]) : new List<FilterData>();
            string sort = !string.IsNullOrEmpty(Request.QueryString["sort"]) ? Request.QueryString["sort"] : "ID";
            string direction = !string.IsNullOrEmpty(Request.QueryString["direction"]) ? Request.QueryString["direction"] : "ASC";

            dynamic model = null;
            int total = 0;

            if (filters.Count > 0)
            {
                model = Departments.RetrieveByFilterAndPage(filters, page, pagesize, sort, direction);
                total = Departments.RetrieveByFilter(filters);
            }
            else
            {
                model = Departments.RetrieveByFilterAndPage(page, pagesize, sort, direction);
                total = Departments.RetrieveByFilter();
            }
            
            if (total > 0) return View(model);
            else return View("Empty");
        }

        public ActionResult AjaxPaging()
        {
            int pagesize = 10;
            int page = Request.QueryString["page"] != null ? Convert.ToInt16(Request.QueryString["page"]) : 1;
            string sort = Request.QueryString["sort"] != null ? Request.QueryString["sort"] : "ID";
            string direction = Request.QueryString["direction"] != null ? Request.QueryString["direction"] : "ASC";
            List<FilterData> filters = Request.Form["filter"] != null ? new JavaScriptSerializer().Deserialize<List<FilterData>>(Request.Form["filter"]) : new List<FilterData>();
            int total = 0;

            if (filters.Count > 0)
            {
                total = Departments.RetrieveByFilter(filters);
            }
            else
            {
                total = Departments.RetrieveByFilter();
            }

            PagingGenerated pager = new PagingGenerated(page, pagesize, total, "/Department/AjaxTable", true, ">> next", true, "<< previous");
            ViewData["Pagination"] = pager.PaginationLink();

            return View();
        }

        //
        // GET: /Department/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Department/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here
                if (ModelState.IsValid)
                {
                    Department department = new Department
                    {
                        Rowstatus = Convert.ToBoolean(collection["Rowstatus"]),
                        Description = collection["Description"],
                        CreatedBy = UserAuthenticated.isAuthenticated ? UserAuthenticated.authUser.FirstName : "DEFAULT",
                        CreatedOn = DateTime.Now
                    };

                    db.Departments.AddObject(department);
                    db.SaveChanges();
                }

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        
        //
        // GET: /Department/Edit/5
 
        public ActionResult Edit(int id)
        {
            Department department = db.Departments.Single(d => d.ID == id);
            return View(department);
        }

        //
        // POST: /Department/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here
                if (ModelState.IsValid)
                {
                    Department department = db.Departments.First(d => d.ID == id);
                    department.Rowstatus = Convert.ToBoolean(collection["Rowstatus"]);
                    department.Description = collection["Description"];
                    department.LastModifiedBy = UserAuthenticated.isAuthenticated ? UserAuthenticated.authUser.FirstName : "DEFAULT";
                    department.LastModifiedOn = DateTime.Now;

                    db.Departments.ApplyCurrentValues(department);
                    db.SaveChanges();
                }

                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                ViewData["Message"] = ex.Message.ToString();
                return View();
            }
        }

        //
        // GET: /Department/Delete/5

        public ActionResult Delete(int id)
        {
            Department department = db.Departments.Single(d => d.ID == id);
            IEnumerable<Section> sections = db.Sections.Where(s => s.DepartmentID == id);
            foreach (Section section in sections)
            {
                db.Sections.DeleteObject(section);
            }

            IEnumerable<JobDescription> jobdescs = db.JobDescriptions.Where(j => j.DepartmentID == id);
            IEnumerable<JobDescResponsibility> respons;
            IEnumerable<JobDescRelationShip> relations;
            IEnumerable<PerformanceIndicator> indicators;
            foreach (JobDescription jobdesc in jobdescs)
            {
                respons = db.JobDescResponsibilities.Where(j => j.JobDescriptionID == jobdesc.ID);
                foreach (JobDescResponsibility respon in respons)
                {
                    indicators = db.PerformanceIndicators.Where(p => p.JobDescResponsibilityID == respon.ID);
                    foreach (PerformanceIndicator indicator in indicators)
                    {
                        db.PerformanceIndicators.DeleteObject(indicator);
                    }

                    db.JobDescResponsibilities.DeleteObject(respon);
                }

                relations = db.JobDescRelationShips.Where(j => j.JobDescriptionID == jobdesc.ID);
                foreach (JobDescRelationShip relation in relations)
                {
                    db.JobDescRelationShips.DeleteObject(relation);
                }

                db.JobDescriptions.DeleteObject(jobdesc);
            }

            IEnumerable<JobTitle> jobs = db.JobTitles.Where(j => j.DepartmentID == department.ID);
            IEnumerable<Account> accounts;
            foreach (JobTitle job in jobs)
            {
                accounts = db.Accounts.Where(a => a.JobTitleID == job.ID);
                foreach (Account account in accounts)
                {
                    db.Accounts.DeleteObject(account);
                }

                db.JobTitles.DeleteObject(job);
            }

            db.Departments.DeleteObject(department);
            db.SaveChanges();

            return RedirectToAction("Index");
        }
    }
}
